package cn.wolfcode.web.controller;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.feign.AliPayFeignApi;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.mysql.cj.protocol.WriterWatcher;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.omg.PortableInterceptor.ObjectReferenceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.util.calendar.LocalGregorianCalendar;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private AliPayFeignApi aliPayFeignApi;
    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;

    @RequestMapping("/alipay")
    public Result<String> alipay(String orderNo, int type){
        //进行参数效验
        if(StringUtils.isEmpty(orderNo) || StringUtils.isEmpty(type + "")){
            throw new BusinessException(SeckillCodeMsg.OPT_SECKILL_ERROR);
        }
        //判断类型是在线支付还是积分支付
        if(OrderInfo.PAYTYPE_ONLINE.equals(type)){
            //在线支付需要远程调用支付服务
            String formString  = orderInfoService.payOnline(orderNo,type);
            return Result.success(formString);
        }else if(OrderInfo.PAYTYPE_INTERGRAL.equals(type)){
            //积分流程支付
            orderInfoService.payIntegral(orderNo,type);
        }else{
            throw new BusinessException(SeckillCodeMsg.OPT_SECKILL_ERROR);
        }
        return Result.success("");
    }

    /**
     * 同步：用于展示订单详情页面
     * @param params
     * @param
     * @return
     */
    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam Map<String,String> params,HttpServletResponse response) throws IOException {
        System.err.println("同步时间：" + new Date());
        //验签操作
        //boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        //远程调用支付服务
        Result<Boolean> result = aliPayFeignApi.rsaCheckV1(params);
        String orderNo = params.get("out_trade_no");
        if(result != null && !result.hasError()){
            if(result.getData()){
                //如果验签通过返回true，跳转到订单详情页面
               response.sendRedirect(frontEndPayUrl + orderNo);
            }else{
                //如果为false，跳转错误页面
                response.sendRedirect("http://localhost/error.html");
            }
        }
    }

    /**
     * 异步：执行具体的业务逻辑
     */
    @RequestMapping("/notify_url")
    public void notifyUrl(@RequestParam Map<String,String> params,HttpServletResponse response) throws IOException {
        System.out.println("异步时间：" + new Date());
        String orderNo = params.get("out_trade_no");
        Result<Boolean> result = aliPayFeignApi.rsaCheckV1(params);
        PrintWriter out = response.getWriter();
        if(result != null && !result.hasError()){
            if(result.getData()){
                //成功，需返回一个success的字符串标识
                orderInfoService.paySuccess(orderNo);
                out.write("success");
            }else{
                out.write("fail");
            }
        }
    }

    @RequestMapping("/refund")
    public Result<String> refund(String orderNo){
        //参数效验
        if(StringUtils.isEmpty(orderNo)){
            throw new BusinessException(SeckillCodeMsg.OPT_SECKILL_ERROR);
        }
        //根据订单编号向redis中查询orderInfo，并判断状态，是在线支付还是积分支付
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if(OrderInfo.PAYTYPE_ONLINE.equals(orderInfo.getPayType())){
            //支付退款流程
            orderInfoService.refundOnline(orderInfo);
        }else if(OrderInfo.PAYTYPE_INTERGRAL.equals(orderInfo.getPayType())){
            //积分退款流程
            orderInfoService.refundIntergral(orderInfo);
        }else{
            throw new BusinessException(SeckillCodeMsg.OPT_SECKILL_ERROR);
        }
        return Result.success("");
    }
}
